import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Button, DatePicker, Row, Col, Select, Table } from 'antd';
import moment from 'moment';

moment.locale('zh_CN');

const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
const Option = Select.Option;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

class Mechanism extends Component {
  constructor(props) {
    super(props);
    this.dataSource = [];
    this.excelData = [];
    this.temp = {
      idx: 0,
      id: '',
    };
    this.temp1 = {
      idx: 0,
      id: '',
    };
  }
  componentDidMount() {
    this.handleSubmit(1);
  }
  componentWillUnmount() {
    this.props.dispatch({
      type: 'settlement/clear',
    });
  }
  handleSubmit = () => {
    const { form, dispatch, root } = this.props;
    const { busniessLst = {} } = root;
    form.validateFields((err, values) => {
      if (!err) {
        this.temp = {
          idx: 0,
          id: '',
        };
        this.temp1 = {
          idx: 0,
          id: '',
        };
        this.dataSource = [];
        this.excelData = [];
        const reqData = {};
        Object.keys(values).forEach((item) => {
          if (values[item]) {
            reqData[item] = values[item];
          }
        });
        reqData.ym = moment(reqData.ym).format('YYYYMM');
        this.ym = reqData.ym;
        delete reqData.time;
        dispatch({
          type: 'settlement/getMechanismLst',
          payload: {
            ...reqData,
          },
        }).then(() => {
          const dataSource = [];
          const excelData = [];
          const { reconciliateLst = [] } = this.props.settlement;
          if (reconciliateLst.merchantList && reconciliateLst.merchantList.length) {
            reconciliateLst.merchantList.forEach((item) => {
              if (item.items && item.items.length) {
                item.items.forEach((item1) => {
                  dataSource.push({
                    ...item1,
                    totalFee: item.totalFee,
                    totalprofit: item.totalprofit,
                    merchantName: item.merchantName,
                    dataLength: item.items.length,
                  });
                  excelData.push({
                    查询月份: item.ym,
                    商户名称: item.merchantName,
                    商户号: item.merchantNo,
                    交易数量: item1.count,
                    交易金额: item1.fee,
                  });
                });
              }
            });
            this.dataSource = dataSource;
            this.excelData = excelData;
          }
          this.columns = [{
            title: '账单生成时间（月）',
            render: (value, row, index) => {
              const obj = {
                props: {},
                children: row.ym || '',
              };
              if (index == 0) {
                obj.props.rowSpan = dataSource.length;
              } else {
                obj.props.rowSpan = 0;
              }
              return obj;
            },
          }, {
            title: '机构编号',
            dataIndex: 'merchantNo',
            key: 'merchantNo',
          }, {
            title: '机构名称',
            dataIndex: 'merchantName',
            key: 'merchantName',
          }, {
            title: '申请数据',
            dataIndex: 'business',
            render: (val) => {
              return val && busniessLst[val] ? busniessLst[val].name : '';
            },
          }, {
            title: '单笔金额（元）',
            dataIndex: 'singleFee',
          }, {
            title: '账单记录条数',
            dataIndex: 'count',
          }, {
            title: '账单金额',
            dataIndex: 'fee',
            render: (val) => {
              return val || '0.00';
            },
          }, {
            title: '总金额（元）',
            render: (value, row) => {
              const obj = {
                props: {},
                children: row.totalFee || '0.00',
              };
              if (row.dataLength != this.temp1.idx || row.merchantNo != this.temp1.id) {
                obj.props.rowSpan = row.dataLength;
              } else {
                obj.props.rowSpan = 0;
              }
              this.temp1 = {
                idx: row.dataLength,
                id: row.merchantNo,
              };
              return obj;
            },
          }, {
            title: '总利润（元）',
            render: (value, row) => {
              const obj = {
                props: {},
                children: row.totalprofit || '0.00',
              };
              if (row.dataLength != this.temp.idx || row.merchantNo != this.temp.id) {
                obj.props.rowSpan = row.dataLength;
              } else {
                obj.props.rowSpan = 0;
              }
              this.temp = {
                idx: row.dataLength,
                id: row.merchantNo,
              };
              return obj;
            },
          }];
          this.setState({
            name: '11',
          });
        });
      }
    });
  }
  openDrawer = () => {
    this.props.dispatch({
      type: 'root/openDrawer',
    });
  }
  handleReset = () => {
    this.props.form.resetFields();
    this.handleSubmit();
  }
  downExcle = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'settlement/getMechanismDownloadFileNm',
      payload: {
        ym: this.ym,
      },
    });
  }
  render() {
    const { form, settlement } = this.props;
    const { reconciliateLst = {} } = settlement;
    const { getFieldDecorator } = form;
    const { sumFee = '0.00', profit = '0.00' } = reconciliateLst;
    return (
      <div className="g-pages merchant-order-pages">
        <Form
          className="g-form"
          hideRequiredMark={true}
          onSubmit={(e) => {
            e.preventDefault();
            this.handleSubmit();
          }}
        >
          <Row>
            <Col span={8}>
              <FormItem {...formItemLayout} label="查询时间">
                { getFieldDecorator('ym', {
                  initialValue: moment(new Date(), 'YYYY-MM'),
                  rules: [{
                    required: 'Y',
                    message: '请选择查询月份',
                  }],
                })(
                  <MonthPicker
                    style={{width: '100%'}}
                    placeholder="请选择查询月份"
                  />,
                )}
              </FormItem>
            </Col>
            <Col span={8} style={{paddingLeft: 24}}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button className="ant-col-offset-1" onClick={() => this.handleReset()}>重置</Button>
            </Col>
          </Row>
        </Form>

        <div className="g-table-cell">
          <div style={{marginBottom: 10, textAlign: 'right'}}>
            <Button
              disabled={!this.excelData.length}
              type="primary"
              onClick={() => this.downExcle()}
            >下载机构对账单</Button>
          </div>
          <Table
            id="table-to-xls"
            bordered
            columns={this.columns}
            dataSource={this.dataSource || []}
            pagination={false}
            rowKey={(record) => {
              return `${record.profit}${record.fee}${record.count}`;
            }}
            footer={() => {
              return (
                this.dataSource.length ?
                  <div style={{fontSize: 14}} className="table-footer-cell">
                    <div style={{display: 'flex', marginBottom: 10, paddingBottom: 10, borderBottom: '1px solid #e9e9e9', justifyContent: 'space-between'}}>
                      <span>总计</span>
                      <span>{sumFee}元</span>
                    </div>
                    <div style={{display: 'flex', justifyContent: 'space-between'}}>
                      <span>利润</span>
                      <span>{profit}元</span>
                    </div>
                  </div> : null
              );
            }}
          />
        </div>
      </div>
    );
  }
}


export default connect((state) => {
  return {
    settlement: state.settlement,
    root: state.root,
  };
})(Form.create()(Mechanism));
